package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.mail.EmailUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/custom")
public class SysCustomController extends BaseController
{

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private EmailUtils emailUtils;

    @Autowired
    private MessageUtil messageUtil;

    /**
     * 获取客户列表
     */
    @PreAuthorize("@ss.hasPermi('system:custom:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "客户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "客户数据");
    }

    @Log(title = "客户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "客户数据");
    }

    /**
     * 根据客户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:custom:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        //获取上级的集合
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            //获取 上级集合字段
            if(sysUser != null){
                String superior = sysUser.getSuperior();
                if(StringUtils.isNotEmpty(superior)){
                    Long[] superiorIds = StringToLong(superior.split(","));
                    sysUser.setSuperiorIds(superiorIds);
                }
            }
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            List<SysRole> roles = roleService.selectRoleAll();
            ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
            ajax.put("posts", postService.selectPostAll());
            if (StringUtils.isNotNull(userId))
            {
                ajax.put("postIds", postService.selectPostListByUserId(userId));
                ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
            }

        }
        return ajax;
    }

    public static Long[] StringToLong(String[] str) {
        Long[] arr = new Long[str.length];
        for (int i = 0; i < str.length; i++) {
            arr[i] = Long.parseLong(str[i]);
        }
        return arr;
    }


    /**
     * 新增客户
     */
    @PreAuthorize("@ss.hasPermi('system:custom:add')")
    @Log(title = "客户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增客户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增客户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增客户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改客户
     */
    @PreAuthorize("@ss.hasPermi('system:custom:edit')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改客户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改客户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        if(StringUtils.isNotEmpty(user.getEmail())){
            user.setUserName(user.getEmail());
        }
        return toAjax(userService.updateUser(user));
    }


    /**
     * 审核客户
     */
    @PreAuthorize("@ss.hasPermi('system:custom:audit')")
    @PutMapping("/audit")
    @Log(title = "客户管理", businessType = BusinessType.AUDIT)
    public AjaxResult audit(@Validated @RequestBody SysUser user) throws ClientException {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            return error("审核客户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("审核客户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("审核客户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        //判断当前传递的审核状态，如果是审核通过，则账号解冻，如果是不通过，则账号冻结
        String newAuditStatus = user.getAuditStatus();
        if(newAuditStatus.equals("1")){//通过
            user.setStatus("0");
        }else if(newAuditStatus.equals("2")){
            user.setStatus("1");
        }

        int n = userService.updateUser(user);
        //先根据客户id获取信息
        SysUser sysUser = userService.selectUserById(user.getUserId());
        if(sysUser != null){
            String registerType = sysUser.getRegisterType();
            String auditStatus = sysUser.getAuditStatus();//数据库中的审核状态（0的时候执行）
            if(StringUtils.isNotEmpty(registerType) && registerType.equals("2") && StringUtils.isNotEmpty(auditStatus) && auditStatus.equals("1")){ //邮箱注册
                //获取邮箱
                String email = sysUser.getEmail();
                if(StringUtils.isNotEmpty(email)){
                    Map valueMap = new HashMap();
                    valueMap.put("to",email);
                    valueMap.put("title","尊敬的用户" + sysUser.getNickName());
                    valueMap.put("content","您的邮箱已经绑定成功，可以使用邮箱密码登录");
                    String thymeleaf="";
                    emailUtils.sendMail(valueMap,thymeleaf);
                }
            }else if(StringUtils.isNotEmpty(registerType) && registerType.equals("1") && StringUtils.isNotEmpty(auditStatus) && auditStatus.equals("1")){ //手机注册
                //获取手机
                String phonenumber = sysUser.getPhonenumber();
                if(StringUtils.isNotEmpty(phonenumber)){
                    JSONObject obj = new JSONObject();
                    obj.put("phone", phonenumber);
                    messageUtil.sendSms(phonenumber, "SMS_462260113", obj);
                }
            }
        }

        return toAjax(n);
    }
    /**
     * 删除客户
     */
    @PreAuthorize("@ss.hasPermi('system:custom:remove')")
    @Log(title = "客户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前客户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }



    /**
     * 修改密码
     */
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {

        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:custom:edit')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeCustomStatus")
    public AjaxResult changeCustomStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据客户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:custom:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 客户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:custom:edit')")
    @Log(title = "客户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:custom:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }


    /**
     * 获取已注册已审核客户表
     */
    @GetMapping("/isRegisterUserlist")
    public AjaxResult isRegisterUserlist(SysUser user)
    {
        //逻辑为已注册的已审核用户，且是同部门的，deptName相同或者deptId相同
        return success(userService.isRegisterUserlist(user));
    }

    /**
     * 设置上级     */
    @PreAuthorize("@ss.hasPermi('system:custom:setSuperior')")
    @PutMapping("/setSuperior")
    @Log(title = "客户管理", businessType = BusinessType.SETSUPERIOR)
    public AjaxResult setSuperior(@Validated @RequestBody SysUser user)
    {
         /*
            1、判断当前选择的上级，是否已经被设置过
            2、根据userId获取当前选择客户是否已经被设置过上级
         */

        String returnSuperior = userService.getSuperior(user.getUserId());
        user.setUpdateBy(getUsername());
        if(StringUtils.isNotEmpty(returnSuperior)){ //不为空，则判断是否已经存在
            Long[] superiorIds = user.getSuperiorIds();
            if(superiorIds!=null && superiorIds.length > 0){
                for(int i = 0 ; i < superiorIds.length; i ++){
                    if(returnSuperior.contains(superiorIds[i].toString())){ //包含，则提示已经设置过
                        continue;
                    }else { //不包含，则重新设置
                        returnSuperior += "," + superiorIds[i].toString();
                        user.setSuperior(returnSuperior);
                    }
                }
            }
        }
        return toAjax(userService.setSuperior(user));
    }


    //根据部门id获取用户id，排除自身
    @GetMapping("/getUserListByDeptId")
    public AjaxResult getUserListByDeptId(SysUser user)
    {
        List<SysUser> list = userService.getUserListByDeptId(user);
        return success(list);
    }

    /**
     * 修改手机号     */
    @PutMapping("/updatePhone")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    public AjaxResult updatePhone(@Validated @RequestBody SysUser user)
    {
        String code = user.getCode();
        System.out.println("登录验证码：" +code);
        String uuid = user.getUuid();
        if(StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(uuid)){
            //从redis中获取
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + code + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if(!code.equals(captcha)){
                return AjaxResult.error("验证码不正确");
            }
        }else{
            return AjaxResult.error("验证码不能为空");
        }
        return toAjax(userService.updateUser(user));
    }


    //根据部门id获取用户id，排除自身
    @GetMapping("/getUserListByDeptName")
    public AjaxResult getUserListByDeptName(SysUser user)
    {
        List<SysUser> list = userService.getUserListByDeptName(user);
        return success(list);
    }


    /**
     * 获取客户列表
     */
    @GetMapping("/unAuditStatuslist")
    public TableDataInfo unAuditStatuslist(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

}
